//
// Created by fazhehy on 2024/5/12.
//

#include "common_inc.h"

uint32_t start = 500;
void Main()
{
    bool start_flag = false;
    RetargetInit(&huart1);
    st7789_init();
    while (nrf24l01_check());
    nrf24l01_init();
    nrf24l01_set_rx_mode();
    HAL_TIM_Base_Start_IT(&htim4);
    adc_init();
    flash_read_parameter();
//    flash_write_default();
//    flash_write_parameter();
    menu_init();
    protocol_init();
    while (!protocol_check()){
        st7789_printf(40, 20, "selfCheck Error");
    }
    st7789_printf(40, 20, "               ");
    remote.protocolState = 0;
    for (;;){
//        st7789_printf(0, 40, "%f", mz_k);
        if (remote.protocolState == 1){
            if (remote.protocolType == 'D'){
                CDC_Transmit_FS(remote.receiveBuffer+2, remote.receiveBufferLen);
            }
            remote.protocolState = 0;
        }
        menu_task();
//        printf("%ld\n", HAL_GetTick()-start);
        if ((HAL_GetTick()-start) <= 100){
            if (!start_flag){
                HAL_TIM_Base_Start_IT(&htim2);
                start_flag = true;
            }
        }
        else{
            if (start_flag){
                HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_SET);
                HAL_TIM_Base_Stop_IT(&htim2);
                start_flag = false;
            }
        }
    }
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if (htim->Instance == htim2.Instance){
        HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_8);
    }
    if (htim->Instance == htim3.Instance){
        if (adc_value[0] <= 2300){
            remote.state = BATTERY_ERROR;
            HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, GPIO_PIN_SET);
        }
        else{
            remote.state = NORMAL;
            HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, GPIO_PIN_RESET);
        }
    }
    else if (htim->Instance == htim4.Instance){
        if (remote.transmitBufferLen != 0){
            nrf24l01_set_tx_mode();
            nrf24l01_transmit_callback();
            if (transmit_flag == 0){
                remote.state = TRANSMIT_ERROR;
            }
            else{
                remote.state = NORMAL;
            }
            remote.transmitBufferLen = 0;
            nrf24l01_set_rx_mode();
        }
    }
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    nrf24l01_receive_callback(GPIO_Pin);
}
